package nl.boelen.game.client.connection;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import nl.boelen.game.net.packet.Packet;
import nl.boelen.game.options.Option;

public class ClientUDP extends Thread {

    private InetAddress ipAddress;
    private DatagramSocket socket;
    private ClientPacketHandler packetHandler;

    public ClientUDP(ClientPacketHandler packetHandler, String ipAddress) {
        this.packetHandler = packetHandler;
        try {
            this.socket = new DatagramSocket();
            this.ipAddress = InetAddress.getByName(ipAddress);
        } catch (SocketException e) {
            e.printStackTrace();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
    }

    public void run() {
        while (true) {
            byte[] data = new byte[1024];
            DatagramPacket packet = new DatagramPacket(data, data.length);
            try {
                socket.receive(packet);
                sleep(1);
            } catch (IOException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            packetHandler.parsePacket(packet.getData(), packet.getAddress(), packet.getPort());
        }
    }

    public void sendPacket(Packet packet) {
        DatagramPacket dataPacket = new DatagramPacket(packet.getData(), packet.getData().length, ipAddress, Option.ServerPort);
        try {
            socket.send(dataPacket);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    public int getUDPPort(){
        return socket.getLocalPort();
    }
}
